package com.qf.web;

import com.qf.domain.Student;
import com.qf.service.StudentRegisterService;
import com.qf.service.impl.StudentRegisterServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/register")
public class AdminRegisterController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        try {
            //处理响应中文的乱码问题
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("utf-8");
            StudentRegisterService adminService = new StudentRegisterServiceImpl();
            //---------------异步校验注册账号是否存在--
//            String count = request.getParameter("username");
//            boolean b = adminService.checkService(count);
//            if(b){
//                response.getWriter().write("yes");
//                return;//结束当前方法,通俗的来讲后面代码不再执行了
//            }
//            //--------------------------
            //1.获取注册页面提交的账号信息
            Map<String, String[]> map = request.getParameterMap();
            //2.封装到Admin这个bean对象
            Student stud = new Student();
            BeanUtils.populate(stud,map);
            //3.创建业务层对象Service
            //AdminService adminService = new AdminServiceImpl();
            boolean register = adminService.register(stud);
            //4.判断注册是否成功
            //5.资源跳转
            if(register==true){
                //注册成功,跳转到登录页面
                response.sendRedirect(
                        "http://localhost:8080/"+
                                request.getContextPath()+  //获取部署的项目访问路径
                                "/admin/login.jsp"
                        );
            }else{
                //注册失败,跳转到注册页面
                request.setAttribute("registerError","注册失败");
                request.getRequestDispatcher("admin/register.jsp").forward(request,response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }
}
